package com.example.day01_weather.mvp.model;

import com.example.day01_weather.bean.CityBean;
import com.example.day01_weather.bean.WeatherBean;
import com.example.day01_weather.mvp.view.ICallBack;
import com.example.day01_weather.mvp.view.IWeather;
import com.example.day01_weather.net.HttpManger;

import java.io.IOException;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 *
 */
public class Model implements IWeather.IModel {

    @Override
    public void getCityData(ICallBack callBack) {
        new HttpManger().getApiService().getCity().enqueue(new retrofit2.Callback<CityBean>() {
            @Override
            public void onResponse(Call<CityBean> call, Response<CityBean> response) {
                callBack.onSuccess(response.body());
            }

            @Override
            public void onFailure(Call<CityBean> call, Throwable t) {
                callBack.onError(t.getMessage());
            }
        });
    }

    @Override
    public void getWeatherData(Map<String, String> map, ICallBack callback) {
        new HttpManger().getApiService().queryWeathcer(map).enqueue(new Callback<WeatherBean>() {
            @Override
            public void onResponse(Call<WeatherBean> call, Response<WeatherBean> response) {
                if(response.code() == 200){
                    callback.onSuccess(response.body());
                }else{
                    try{
                        String str = response.errorBody().string().toString();
                        callback.onError(str);
                    }catch (IOException e){
                        callback.onError(e.getMessage());
                    }
                }

            }

            @Override
            public void onFailure(Call<WeatherBean> call, Throwable t) {
                callback.onError(t.getMessage());

            }
        });
    }


}
